package com.ruoyi.wss;

import com.ruoyi.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 端点：ws://ip:port/websocket/platform/{platformId}
 */

@Slf4j
@Component
@ServerEndpoint("/websocket/platform/{platformId}")
public class WebSocketServer {

    // 当前节点内存中的会话
    public static final Map<String, Session> LOCAL_SESSIONS = new ConcurrentHashMap<>();
    private static final String REDIS_KEY = "parking:conn";
    private static StringRedisTemplate redisTemplate;
    private static WebSocketMessageService webSocketMessageService;

    @Autowired
    public void setWebSocketMessageService(WebSocketMessageService webSocketMessageService) {
        WebSocketServer.webSocketMessageService = webSocketMessageService;
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        WebSocketServer.redisTemplate = redisTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("platformId") String platformId) throws IOException{

        String query = session.getQueryString();          // 例如：v=1.0
        String version = query == null ? "1.0" : query.split("=")[1];

        // 1) 内存
        LOCAL_SESSIONS.put(platformId, session);

        // 2) Redis：写入 platformId -> {sessionId,version}
        DeviceConnVO vo = new DeviceConnVO(session.getId(), version);
        redisTemplate.opsForHash().put(REDIS_KEY, platformId, JsonUtil.toJson(vo));

        // 3) 返回握手成功
        session.getBasicRemote().sendText("连接成功" + platformId);

        log.info("WebSocket连接建立： {}，内容：", platformId, session.getId());
    }

    @OnMessage
    public void onMessage(@PathParam("platformId") String platformId, String message) {
        log.info("WebSocket收到消息： {}，内容：{}", platformId, message);
        try {
            webSocketMessageService.handle(platformId, message);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("WebSocket处理消息时发生异常： {}，内容：{}", platformId, e.getMessage());
        }
    }

    @OnClose
    public void onClose(@PathParam("platformId") String platformId, CloseReason closeReason) {
        LOCAL_SESSIONS.remove(platformId);
        redisTemplate.opsForHash().delete(REDIS_KEY, platformId);
        log.info("WebSocket连接关闭： {}，原因：{}", platformId, closeReason);
    }

    @OnError
    public void onError(@PathParam("platformId") String platformId, Throwable throwable) {
        log.error("WebSocket发生异常： {}，内容：{}", platformId, throwable);
    }

}
